#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>//消息对话框

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    searchCom();
    tcpServr=new QTcpServer (this);
    myport=new QSerialPort();//实例化
    timer = new QTimer;
}

Widget::~Widget()
{
    //用完删除，释放资源
    delete ui;
    delete tcpServr;
    delete tcpSocket;
    delete myport;
    delete timer;
}

//遍历串口
void Widget::searchCom()
{
    foreach(QSerialPortInfo info,QSerialPortInfo::availablePorts())
    {
        ui->comboBox_Com->addItem(info.portName());
    }

}


//有客服端发起连接时触发
void Widget::newConnected()
{
    tcpSocket = tcpServr->nextPendingConnection();//获取
    QString ip=tcpSocket->peerAddress().toString();
    quint16 port=tcpSocket->peerPort();
    connect(tcpSocket, &QTcpSocket::readyRead, this, &Widget::readData);
}
//有客户端发来数据时
void Widget::readData()
{
    QByteArray recv=tcpSocket->readAll();//接受数据
    myport->write(recv);//发送数据
}
//开始监听
void Widget::on_btn_listen_clicked()
{
    QString ip=ui->lineEdit_ip->text().trimmed();
    int port = ui->lineEdit_port->text().toUInt();
    bool res = tcpServr->listen(QHostAddress(ip),port);
    if(res)
    {
        ui->btn_close->setEnabled(true);
        ui->btn_listen->setEnabled(false);
        connect(tcpServr, &QTcpServer::newConnection, this, &Widget::newConnected);
    }
    else
    {
        QMessageBox::warning(this,"提示","监听失败");
    }
}
//关闭
void Widget::on_btn_close_clicked()
{
    tcpServr->close();
    tcpSocket->close();
    ui->btn_listen->setEnabled(true);
    ui->btn_close->setEnabled(false);
}
//打开串口
void Widget::on_btn_Com_open_clicked()
{
    myport->setPortName(ui->comboBox_Com->currentText());
    if(ui->comboBox_btv->currentText()=="9600")//波特率
    {
        myport->setBaudRate(QSerialPort::Baud9600);
    }
    if(ui->comboBox_Data->currentText()=="8")//数据位
    {
       myport->setDataBits(QSerialPort::Data8);
    }
    if(ui->comboBox_Ven->currentText()=="NONE")//校验位
    {
        myport->setParity(QSerialPort::NoParity);
    }
    if(ui->comboBox_stop->currentText()=="1")//停止位
    {
        myport->setStopBits(QSerialPort::OneStop);
    }
    bool res=myport->open(QIODevice::ReadWrite);
    if(!res)
    {
        QMessageBox::warning(this,"提示",ui->comboBox_Com->currentText()+"串口打开失败");
        return;
    }
    ui->btn_Com_open->setEnabled(false);//打开成果变灰
    ui->btn_Com_close->setEnabled(true);
}

//关闭串口
void Widget::on_btn_Com_close_clicked()
{
    if(myport->isOpen())
    {
         myport->close();
         ui->btn_Com_open->setEnabled(true);
    }
}


void Widget::String2Hex(QString str, QByteArray &senddata)

{
    int hexdata,lowhexdata;
        int hexdatalen = 0;
        int len = str.length();
        senddata.resize(len/2);
        char lstr,hstr;
        for(int i=0; i<len; )
        {
            //char lstr,
            hstr=str[i].toLatin1();
            if(hstr == ' ')
            {
                i++;
                continue;
            }
            i++;
            if(i >= len)
                break;
            lstr = str[i].toLatin1();
            hexdata = ConvertHexChar(hstr);
            lowhexdata = ConvertHexChar(lstr);
            if((hexdata == 16) || (lowhexdata == 16))
                break;
            else
                hexdata = hexdata*16+lowhexdata;
            i++;
            senddata[hexdatalen] = (char)hexdata;
            hexdatalen++;
        }
        senddata.resize(hexdatalen);
}
char Widget::ConvertHexChar(char ch)
{
    if((ch >= '0') && (ch <= '9'))
            return ch-0x30;
        else if((ch >= 'A') && (ch <= 'F'))
            return ch-'A'+10;
        else if((ch >= 'a') && (ch <= 'f'))
            return ch-'a'+10;
        else return (-1);
}



